﻿using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using System.Windows;
using XYAC.Framework.WohuaMesExtend.IHI.DataContext;
using XYAC.Framework.WohuaMesExtend.IHI.Extensions;
using XYAC.Framework.WohuaMesExtend.IHI.LocalData.Context;
using XYAC.Framework.WohuaMesExtend.IHI.OracleRemoteDB;
using XYAC.Framework.WohuaMesExtend.IHI.Services;
using XYAC.Framework.WohuaMesExtend.IHI.ViewModels;
using XYAC.Framework.WohuaMesExtend.IHI.Views;

namespace XYAC.Framework.WohuaMesExtend.IHI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public App()
        {

            Environment.CurrentDirectory = Path.GetDirectoryName(this.GetType().Assembly.Location);//设置工作目录
            try
            {
                this.EventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, ProcessSingleInstance.EventName);
                ThreadPool.RegisterWaitForSingleObject(this.EventWaitHandle, OnOtherInstanceStarted, null, Timeout.Infinite, true);
            }
            catch (Exception)
            {

            }
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
            this.Tray = new TrayIconManager();
        }

        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            RestartApplication();
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //未处理的异常
            RestartApplication();
        }
        private void OnOtherInstanceStarted(object state, bool timedOut)
        {
            try
            {
                // 当检测到其他实例启动时，激活当前实例的主窗口
                Application.Current.MainWindow.Dispatcher.Invoke(new Action(ActivateMainWindow));
                //this.EventWaitHandle.Reset();
            }
            catch (Exception)
            {

            }
        }

        private static void RestartApplication()
        {
            // 获取当前应用程序的启动路径
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = "DelayStart.vbs", // 或者是 "Delay.bat"
                UseShellExecute = true
            };
            //灾难性故障时重新启动
            Process.Start(startInfo);
        }

        /// <summary>
        /// 日志记录器
        /// </summary>
        private ILogger<App> Logger { get; set; }

        public IHost HostService { get; private set; }
        public EventWaitHandle EventWaitHandle { get; }
        public TrayIconManager Tray { get; }
        WebApplication webApp;

        protected override void OnStartup(StartupEventArgs e)
        {
            //record Person(string Name);

            if (ProcessSingleInstance.AlreadyRunning2())
            {
                Application.Current.Shutdown();
                return;
            }
            else
            {
                RigisterDI();
                
                this.HostService.Start();

                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                using (var scope = HostService.Services.CreateScope())
                {
                    var localDbService = scope.ServiceProvider.GetService<LocalDataService>();
                    var ret = localDbService.CreateDb();

                    //var remoteDbService = scope.ServiceProvider.GetService<OracleMesContext>();
                    //var ret2 = remoteDbService.Database.EnsureCreated();
                }

            }
            base.OnStartup(e);
            
            try
            {
                if (this.HostService != null)
                {
                    var mainWindow = HostService.Services.GetRequiredService<MainWindow>();
                    createWebService();
                    mainWindow.Show();
                }
            }
            catch (Exception)
            {

            }
            WatchDog.WatchDogStarter.StartWatchDog();
        }

        private void createWebService()
        {
            //webApp = WebApplication.Create();
            var builder = WebApplication.CreateBuilder();
            builder.Services.AddCors(options => { });
            var webApp = builder.Build();

            var service=HostService.Services.GetRequiredService<AccessIHIService>();
            var configer= HostService.Services.GetRequiredService<IConfiguration>();

            string BaseUri = configer["AppConfig:BaseUri"];//.BaseUri;// "http://localhost:5100";

            webApp.MapGet("/GetLastDwlDatas", () => new[]
            {
                service.GetLastDwlData()
            });
            webApp.MapGet("/GetLastLaserDatas", () => new[]
            {
                service.GetLastLaserData()
            });
            webApp.MapGet("/GetLastDwlData", () =>JsonSerializer.Serialize(service.GetLastDwlData()));
            webApp.MapGet("/GetLastLaserData", () => JsonSerializer.Serialize(service.GetLastLaserData()));

            webApp.MapGet("/test", () => "Hello World! " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            Task.Run(() => { webApp.RunAsync(BaseUri); });
            //webApp.Run();
        }

        private void ActivateMainWindow()
        {
            var mainWindow = Application.Current.MainWindow;
            if (mainWindow != null)
            {
                mainWindow.Show();
                mainWindow.Activate();
            }
        }

        private void RigisterDI()
        {

            #region 注册DI服务
            var host = Host.CreateDefaultBuilder();

            host.ConfigureLogging(option =>
            {
                // 清除所有默认的日志提供程序
                option.ClearProviders();
                //option.AddProvider(new Log4NetProvider("log4net.config", true));
                option.AddLog4Net("log4net.config");

            });
            host.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var fullPath = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "Configs"));
                config.SetBasePath(fullPath)
                .AddJsonFile("AppConfig.json", optional: false, reloadOnChange: true);
            });
            host.ConfigureServices((hostContext, services) => ConfigureServices(hostContext.Configuration, services));
            this.HostService = host.Build();
            DeleteSuccessFlag();
            this.Logger = this.HostService.Services.GetRequiredService<ILogger<App>>();

            InitializeDatabase();
            #endregion
        }
        private void CreateSuccessFlag()
        {
            try
            {

                using (FileStream fs = File.Create("CorrectHandle"))
                {

                }
            }
            catch (Exception)
            {

            }
        }
        private void DeleteSuccessFlag()
        {
            try
            {

                File.Delete("CorrectHandle");
            }
            catch (Exception)
            {

            }
        }
        private void InitializeDatabase()
        {
            try
            {
                // 创建作用域并使用瞬态服务
                using (var scope = HostService.Services.CreateScope())
                {
                    var localDbService = scope.ServiceProvider.GetRequiredService<LocalDataService>();
                    var ret = localDbService.CreatePreDb();
                    ret = localDbService.CreateDb();
                    ret = localDbService.CreateNextDb();
                    //GC.SuppressFinalize(localDbService);
                }
            }
            catch (Exception ex)
            {
                this.Logger?.LogError(ex.Message, ex);
            }
        }

        private void ConfigureServices(IConfiguration configuration, IServiceCollection services)
        {
            #region 注册数据上下文
            string modStr = "Persist Security Info=False;Mode=Share Deny None;Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\HisData\\DB20250220.mdb;";
            //services.AddDbContextFactory<AccessIHIDbContext>(x =>
            //{
            //    x.UseJet(modStr);
            //});
            services.AddDbContextFactory<AccessIHIDbContext>();
            services.AddDbContext<AccessIHIBaseContext>(ServiceLifetime.Scoped);
            services.AddDbContext<AccessIHIDbContext>(ServiceLifetime.Scoped);//可以改变下生命周期模型
            services.AddDbContext<AccessIHIYesterdayDbContext>(ServiceLifetime.Scoped);
            services.AddDbContext<OracleMesContext>(ServiceLifetime.Scoped);
            services.AddDbContext<LocalDataContext>(ServiceLifetime.Scoped);
            services.AddDbContext<LocalTomorrowDataContext>(ServiceLifetime.Scoped);
            services.AddDbContext<LocalYesterdayDataContext>(ServiceLifetime.Scoped);
            #endregion

            services.AddTransient<LocalDataService>();
            services.AddTransient<YB_TechnologyService>();
            services.AddTransient<YB_LOT_INSPECTService>();
            services.AddTransient<YB_PROCESS_STEPService>();
            services.AddTransient<AccessIHIService>();
            services.AddTransient<HyperDbService>();
            services.AddTransient<YB_LOT_INSPECT_LocalService>();

            services.AddSingleton<MainWindow>();
            services.AddSingleton<MainWindowViewModel>();

            services.AddSingleton<QualityDataHistoryView>();
            services.AddSingleton<QualityDataHistoryViewModel>();



            services.AddSingleton<SystemConfigView>();
            services.AddSingleton<SystemConfigViewModel>();

            services.AddSingleton<TrayIconManager>();
            services.AddSingleton<IConfiguration>(configuration);
            // 注册配置到服务容器

            //services.AddOptions();
            // 使用配置实例配置 AppConfig
            //services.Configure<AppConfig>(configuration);
            services.Configure<AppConfig>(configuration.GetSection("AppConfig"));
        }


    }
}
